package com.flyou.ccnucenter.ui.activity.login;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.domain.MyUser;
import com.flyou.ccnucenter.ui.activity.BaseActivity1;
import com.flyou.ccnucenter.ui.activity.MainActivity;
import com.flyou.ccnucenter.utils.BmobErrorCodeUtils;
import com.flyou.ccnucenter.utils.Md5Parser;
import com.flyou.ccnucenter.utils.RegexPatternUtils;
import com.flyou.ccnucenter.widget.ClearEditText;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.RequestSMSCodeListener;
import cn.bmob.v3.listener.ResetPasswordByCodeListener;

public class GetBackPasswordActivity extends BaseActivity1 implements View.OnClickListener, TextWatcher {
    private RelativeLayout mTitlebarRlBack;
    private TextView mTitlebarTvTitle;
    private String phone;
    private String Md5password;
    private ClearEditText mSetNewPasswordEtPassword;
    private ClearEditText mSetNewPasswordEtRepassword;
    private Button mBt_next_step;
    private ClearEditText mEtPhoneNumber;
    private Button mBtGetVerifitionCode;
    private ClearEditText mEtVerifitionCode;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_get_back_password);

        mTitlebarRlBack = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        mTitlebarTvTitle = (TextView) findViewById(R.id.titlebar_tv_title);

        mSetNewPasswordEtPassword = (ClearEditText) findViewById(R.id.setNewPassword_et_password);
        mSetNewPasswordEtRepassword = (ClearEditText) findViewById(R.id.setNewPassword_et_Repassword);

        mBt_next_step = (Button) findViewById(R.id.bt_next_step);
        mEtPhoneNumber = (ClearEditText) findViewById(R.id.et_phone_number);
        mBtGetVerifitionCode = (Button) findViewById(R.id.bt_get_verifition_code);
        mEtVerifitionCode = (ClearEditText) findViewById(R.id.et_verifition_code);
    }

    @Override
    protected void initDate() {
        mTitlebarTvTitle.setText("找回密码");


    }

    @Override
    protected void setListener() {
        mTitlebarRlBack.setOnClickListener(this);
        mBt_next_step.setOnClickListener(this);
        mBtGetVerifitionCode.setOnClickListener(this);
        mEtVerifitionCode.addTextChangedListener(this);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.titlebar_rl_back:
                finish();
                break;
            case R.id.bt_next_step:

                if (!RegexPatternUtils.isMobile(mEtPhoneNumber.getText().toString().trim())) {
                    Toast.makeText(this, R.string.regex_phone_error, Toast.LENGTH_SHORT).show();
                    return;
                }

                /** 验证验证码*/
                String phone = mEtPhoneNumber.getText().toString().trim();
                String code = mEtVerifitionCode.getText().toString().trim();
                if (mSetNewPasswordEtPassword.getText().toString().trim().isEmpty()
                        || mSetNewPasswordEtRepassword.getText().toString().trim().isEmpty()) {
                    Toast.makeText(this, R.string.regex_password_empty, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!mSetNewPasswordEtPassword.getText().toString().trim().
                        equals(mSetNewPasswordEtRepassword.getText().toString().trim())) {
                    Toast.makeText(this, R.string.regex_password_equals, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!RegexPatternUtils.isPassword(mSetNewPasswordEtPassword.getText().toString().trim())) {
                    Toast.makeText(this, R.string.regex_password_error, Toast.LENGTH_SHORT).show();
                    return;
                }
                Md5password = Md5Parser.md5Parser(mSetNewPasswordEtRepassword.getText().toString().trim());

                VerifitionSmsCode(phone, code);


                break;
            case R.id.bt_get_verifition_code:


                if (!RegexPatternUtils.isMobile(mEtPhoneNumber.getText().toString().trim())) {
                    Toast.makeText(this, R.string.regex_phone_error, Toast.LENGTH_SHORT).show();
                    return;
                }
                /**发送验证码*/
                postVeritftionCode();

                break;
        }


    }


    /*
* 验证验证码
* */
    private void VerifitionSmsCode(final String phone, final String code) {

        BmobUser.resetPasswordBySMSCode(GetBackPasswordActivity.this, code, Md5password, new ResetPasswordByCodeListener() {

            @Override
            public void done(BmobException ex) {
                // TODO Auto-generated method stub
                mProgressDialog.dismiss();
                if (ex == null) {
                    Toast.makeText(GetBackPasswordActivity.this, "密码修改成功,请重新登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(GetBackPasswordActivity.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(GetBackPasswordActivity.this, "修改密码失败" + ex.getMessage() + ex.getErrorCode(), Toast.LENGTH_SHORT).show();
                }
            }
        });





    }


    //验证码监听器
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 6) {
            mBt_next_step.setEnabled(true);

        } else {
            mBt_next_step.setEnabled(false);
        }

    }

    /*
        * 判断是否注册
        * */
    public void postVeritftionCode() {
        mProgressDialog = ProgressDialog.show(GetBackPasswordActivity.this, null, "正在提交数据", false, false);
        BmobQuery<MyUser> query = new BmobQuery<MyUser>();
        query.addWhereEqualTo("mobilePhoneNumber", mEtPhoneNumber.getText().toString().trim());
        query.findObjects(GetBackPasswordActivity.this, new FindListener<MyUser>() {

            @Override
            public void onSuccess(List<MyUser> list) {

                if (list.size() > 0) {
                    PostVerifitionCode(mEtPhoneNumber.getText().toString().trim());
                } else {
                    mProgressDialog.dismiss();
                    Toast.makeText(GetBackPasswordActivity.this, "该手机号尚未注册", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onError(int i, String s) {
                mProgressDialog.dismiss();
                String message = BmobErrorCodeUtils.getMessage(i, s);
                Toast.makeText(GetBackPasswordActivity.this, message, Toast.LENGTH_SHORT).show();

            }
        });

    }

    /*
      * 发送验证码
      * */
    private void PostVerifitionCode(String phone) {

        BmobSMS.requestSMSCode(GetBackPasswordActivity.this, phone, "找回密码", new RequestSMSCodeListener() {

            @Override
            public void done(Integer smsId, BmobException ex) {
                mProgressDialog.dismiss();
                if (ex == null) {
                    new MyCount(60000, 1000).start();
                    Toast.makeText(GetBackPasswordActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(GetBackPasswordActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //    自定义定时器
    class MyCount extends CountDownTimer {
        /**
         * @param millisInFuture    总时间
         * @param countDownInterval 间隔事件
         */
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtGetVerifitionCode.setText("重新发送 " + (int) millisUntilFinished / 1000);
            mBtGetVerifitionCode.setEnabled(false);
        }

        @Override
        public void onFinish() {
            mBtGetVerifitionCode.setText("获取验证码");
            mBtGetVerifitionCode.setEnabled(true);

        }
    }


}
